package com.bankcomm.creditcard.redfriday;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;

import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKLocationManager;
import com.bankcomm.creditcard.redfriday.activity.ActivityActivity;
import com.bankcomm.creditcard.redfriday.activity.ActivityDetailActivity;
import com.bankcomm.creditcard.redfriday.data.GPS;
import com.bankcomm.creditcard.redfriday.shop.ShopTabActivity;
import com.google.zxing.client.android.CaptureActivity;

public class MainActivity extends Activity {
	private GridView mGridView;
	private SimpleAdapter mAdapter;
	private List<Map<String, Object>> mList = new ArrayList<Map<String, Object>>();
	private static final String TAG = "MainActivity";
	private static boolean isFirst = true;
	private OnItemClickListener mItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			Intent intent = (Intent) mList.get(position).get("intent");
			startActivity(intent);
		}

	};

	private LocationListener mLocationListener = new com.baidu.mapapi.LocationListener() {

		@Override
		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			if (location != null) {
				GPS.LAT = location.getLatitude();
				GPS.LNG = location.getLongitude();
				Log.d(TAG, "onLocationChanged: " + location.toString());
			}
		}
	};

	private MKLocationManager mkLocationManager;

	// private LocationListener mLocationListener = new LocationListener() {
	// @Override
	// public void onLocationChanged(Location location) {
	// // TODO Auto-generated method stub
	// GPS.LNG = location.getLongitude();
	// GPS.LAT = location.getLatitude();
	// Log.d(TAG, "onLocationChanged: " + GPS.LNG + ":" + GPS.LAT);
	// }

	// @Override
	// public void onStatusChanged(String provider, int status, Bundle extras) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onProviderEnabled(String provider) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onProviderDisabled(String provider) {
	// // TODO Auto-generated method stub
	//
	// }
	// };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initList();
		mGridView = (GridView) findViewById(R.id.main_gridview);
		mAdapter = new SimpleAdapter(getApplicationContext(), mList,
				R.layout.main_item, new String[] { "image", "name" },
				new int[] { R.id.main_item_imageview, R.id.main_item_name });
		mGridView.setAdapter(mAdapter);
		mGridView.setOnItemClickListener(mItemClickListener);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 环境检测
		checkSys();

	}

	private void checkSys() {
		Builder builder = new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_info)
				.setTitle(R.string.syschecker_msg_title)
				.setMessage(R.string.syschecker_msg_message)
				.setCancelable(false)
				.setNegativeButton(R.string.cancel, new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						finish();
					}
				});

		boolean hasNetwork = true;
		ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = conManager.getActiveNetworkInfo();
		if (info == null) {
			hasNetwork = false;
		}
		if (!hasNetwork) {
			builder.setPositiveButton(R.string.syschecker_open_network,
					new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							// 连网设置
							Intent intent = new Intent();
							intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							intent.setAction(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
							startActivity(intent);
						}
					});
		}

		MyApplication myApplication = (MyApplication) getApplication();
		mkLocationManager = myApplication.getBMapManager().getLocationManager();
		mkLocationManager.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
		mkLocationManager.enableProvider(MKLocationManager.MK_GPS_PROVIDER);
		mkLocationManager.setNoitifyInternal(5, 5);

		boolean hasGPS = true;
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
				&& !locationManager
						.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			hasGPS = false;
		} else {
			if (isFirst) {
				mkLocationManager.requestLocationUpdates(mLocationListener);
				Log.d(TAG, "onCreate: requestLocationUpdates");

				// locationManager.requestLocationUpdates(
				// LocationManager.GPS_PROVIDER, 2000, 10,
				// mLocationListener);
				// Log.d(TAG, "checkSys: add gps location");
				//
				// locationManager.requestLocationUpdates(
				// LocationManager.NETWORK_PROVIDER, 2000, 10,
				// mLocationListener);
				// Log.d(TAG, "checkSys: add network location");
				isFirst = false;
			}
		}

		if (!hasGPS) {
			builder.setNeutralButton(R.string.syschecker_open_gps,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent fireAlarm = new Intent(
									android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							fireAlarm.addCategory(Intent.CATEGORY_DEFAULT);
							startActivity(fireAlarm);
						}
					});
		}

		if (!hasNetwork || !hasGPS) {
			builder.create().show();
		}
	}

	private void initList() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("image", R.drawable.activity);
		map.put("name", getString(R.string.activity));
		Intent intent = new Intent(getApplicationContext(),
				ActivityActivity.class);
		map.put("intent", intent);
		mList.add(map);

		map = new HashMap<String, Object>();
		map.put("image", R.drawable.barcode);
		map.put("name", getString(R.string.barcode));
		intent = new Intent(getApplicationContext(), CaptureActivity.class);
		map.put("intent", intent);
		mList.add(map);

		map = new HashMap<String, Object>();
		map.put("image", R.drawable.shop);
		map.put("name", getString(R.string.shop));
		intent = new Intent(getApplicationContext(), ShopTabActivity.class);
		map.put("intent", intent);
		mList.add(map);

		map = new HashMap<String, Object>();
		map.put("image", R.drawable.fifty);
		map.put("name", getString(R.string.fifty));
		intent = new Intent(getApplicationContext(),
				ActivityDetailActivity.class);
		intent.putExtra("index", BaseActivity.INDEX_FIFTY);
		map.put("intent", intent);
		mList.add(map);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(this).setTitle(R.string.exit_tip)
					.setIcon(android.R.drawable.ic_dialog_info)
					.setPositiveButton(R.string.confirm, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							finish();
						}
					})
					.setNegativeButton(R.string.cancel, new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
						}
					}).show();
		}
		super.onKeyDown(keyCode, event);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		isFirst = true;
		super.onDestroy();
		mkLocationManager.removeUpdates(mLocationListener);
		Log.d(TAG, "onDestroy: removeUpdates");
		// if (mLocationListener != null) {
		// LocationManager locationManager = (LocationManager)
		// getSystemService(Context.LOCATION_SERVICE);
		// locationManager.removeUpdates(mLocationListener);
		// Log.d(TAG, "onDestroy: remove location");
		// }
	}
}